package com.neutech.controller;

import com.google.gson.Gson;
import com.neutech.entity.User;
import com.neutech.service.CartService;
import com.neutech.service.impl.CartServiceImpl;
import com.neutech.util.NumberUtils;
import com.neutech.vo.ResultVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/cart/updateQuantity")
public class UpdateCartQuantity extends HttpServlet {
    private CartService cartService=new CartServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out=resp.getWriter();
        Gson gson =new Gson();
        //获取参数
        String cartId=req.getParameter("id");
        String quantity=req.getParameter("quantity");
        //校验参数
        if (cartId==null){
            out.println(gson.toJson(ResultVO.error(4003,"购物车id不能为空")));
            out.close();
            return;
        }
        if (!NumberUtils.isNumber(cartId)){
            out.println(gson.toJson(ResultVO.error(4003,"购物车id必须是数字")));
            out.close();
            return;
        }
        if (quantity==null){
            out.println(gson.toJson(ResultVO.error(4003,"数量不能为空")));
            out.close();
            return;
        }
        if (!NumberUtils.isNumber(quantity)){
            out.println(gson.toJson(ResultVO.error(4003,"数量必须是个数字")));
            out.close();
            return;
        }
        User user= (User) req.getSession().getAttribute("user");
        //调用业务层
        cartService.updateQuantityById(Integer.parseInt(cartId),Integer.parseInt(quantity),user.getId());
        out.print(gson.toJson(cartService.updateQuantityById(Integer.parseInt(cartId),
                Integer.parseInt(quantity),user.getId())));
        out.close();
    }
}
